<script lang="ts" setup>
import type {FormInstance, FormRules} from 'element-plus'
import {LocationQueryValue, useRoute, useRouter} from "vue-router";
import {UserLoginType} from "@/api/sys/admin/user/types";
import {useUserStore} from "@/store";

const route = useRoute()
const router = useRouter()

const ruleFormRef = ref<FormInstance>()
const formData = reactive<UserLoginType>({
  username: 'admin',
  password: '123456'
})

const rules = reactive<FormRules>({
  username: [
    {required: true, message: '请输入您的用户名', trigger: 'blur'},
    {min: 1, max: 100, message: '用户名长度不小于1', trigger: 'blur'},
  ], password: [
    {required: true, message: '请输入您的密码', trigger: 'blur'},
    {min: 6, max: 100, message: '密码长度不小于6', trigger: 'blur'},
  ],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const userStore = useUserStore()
      const isOkUser = await userStore.loginUser(formData)
      if (isOkUser) {
        const query = route.query;
        const redirect = (query.redirect as LocationQueryValue) ?? "/";

        const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
        );
        await router.push({path: redirect, query: otherQueryParams});
      } else {
        // 登录失败
      }
    }
  })
}

// const resetForm = (formEl: FormInstance | undefined) => {
//  if (!formEl) return
//  formEl.resetFields()
// }
</script>
<template>
  <main class="main">
    <el-form
        ref="ruleFormRef"
        :model="formData"
        :rules="rules"
        label-width="6em"
        status-icon
        label-suffix=":"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"/>
      </el-form-item>
      <el-form-item label-width="10%">
        <el-button class="w-100%" type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-row class="mr-4">
          <el-text>
            <el-text size="large">管理员:</el-text>
            admin 123456
          </el-text>
        </el-row>
        <el-row>
          <el-text>
            <el-text size="large">游客:</el-text>
            guest 123456
          </el-text>
        </el-row>
        <!--    <el-button @click="resetForm(ruleFormRef)">重置</el-button>-->
      </el-form-item>
    </el-form>
  </main>
</template>
<style scoped lang="scss">
.main {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-form {
    padding: 2em;
    border: 1px solid #ccc;
    background-color: #fff;
    border-radius: 1em;

    .el-input {
      width: 20em;
    }
  }
}
</style>